<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\api\controller;

use cmf\controller\HomeBaseController;
use think\cache\driver\Redis;
use think\log;

class LoginController extends HomeBaseController
{
	protected $app_id = 'wxd75acc0ec8579564';
	protected $appsecret = '8fb5cb94f10c963d17929bb7808171c5';


	/**
	*
	*授权登录-登录请求
	**/
	public function wxLogin()
	{
        WL(['msg' => '开始登陆'], 'login_app');
		//接收code
		$code = $this->request->param('code', '');
		if(empty($code))
		{
            return return_msg(2002, '请传递CODE');
		}


		//获取用户OPEN_ID
        WL(['msg' => '获取用户open_Id', 'code' => $code], 'login_app');
		$data = $this->get_access_token($code);//获取access_token和用户openid

         WL(['msg' => '结果', 'code' => $data], 'login_app');
		if(!empty($data['errcode']))
		{
		  return return_msg(2003, $data['errmsg']);
		}

        WL($data, 'login_app');

        //通过open_id,判断用户是否已存在
        WL(['msg' => '查找用户资料'], 'login_app');
        $memModel = new \app\home\model\MemberModel();
        $info = $memModel->getMemberIdWhereOpenId($data['openid'], 'member_id, status');

        //获取用户微信资料
        WL(['msg' => '查找用户微信资料'], 'login_app');
        $wx_info = $this->getMemberInfo($data['access_token'], $data['openid']);
        WL($wx_info, 'login_app');

        //查找用户唯一unionid，匹配用户
        WL(['msg' => 'unionid查找用户信息'], 'login_app');
        if(empty($info))
        {
            $info = $memModel->getMemberIdWhereUnionid($wx_info['unionid'], 'member_id, status');
        }

        WL($wx_info, 'login_app');

        $get_real_ip = get_real_ip();
        $login_time = date('Y-m-d H:i:s');
        if(empty($info))
        {
             WL(['msg' => '注册一条新的信息'], 'login_app');
            //生成邀请码
            $data = [
                'app_open_id' => $data['openid'], 
                'login_time' => $login_time, 
                'login_ip' => $get_real_ip,
                'invite' => $this->cmf_random_string(),
                'unionid' => $wx_info['unionid'],
                'logo' => $wx_info['headimgurl'],
                'nickname' => $this->filterEmoji($wx_info['nickname']),
                'sex' => ($wx_info['sex'] == 1) ? '男' : '女',
            ];

        	//无，注册一条信息
        	$member_id = $memModel->addMemberInfo($data);
        	if(empty($member_id))
        	{
        		return return_msg(2003, '添加用户信息失败，系统错误');
        	}
        }else{

        	//判断用户状态
        	if($info['status'] != 1)
        	{
        		return return_msg(2004, '该账号已被禁用，请联系管理员');
        	}
        	//存在，更新登录时间和IP
        	$member_id = $info['member_id'];
            $update = [
                'app_open_id' => $data['openid'],
                'login_time' => $login_time, 
                'login_ip' => $get_real_ip,
                'logo' => $wx_info['headimgurl'],
                'nickname' => $this->filterEmoji($wx_info['nickname']),
                'sex' => ($wx_info['sex'] == 1) ? '男' : '女',
                ];

            WL(['msg' => '已注册，更新用户资料','member_id' => $member_id], 'login_app');
        	$res = $memModel->updateMemberInfo($info['member_id'], $update);
        }

		//生成用户token
		$token = setMemberToken($data['openid']);

		//存入数据库
		$mtModel = new \app\home\model\MemberTokenModel();
		$res = $mtModel->addMemberTokenInfo(['member_id' => $member_id, 'member_token' => $token]);

		$redis = new Redis();
		$redis->set($token, $member_id, 86400 * 30);

		return return_msg(200, '', ['token' => $token, 'access_token' => $data['access_token']]);
	}


	 /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code){
        $appid = $this->app_id;
        $appsecret =$this->appsecret;

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }


    /**
    *
    *拉取用户资料
    **/
    public function getMemberInfo($access_token, $open_id)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$open_id.'&lang=zh_CN'; 
        $user = json_decode(file_get_contents($url));
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }





    public function cmf_random_string($len = 6)
    {
        $chars    = [
            "A", "B", "C", "D", "E", "F", "G","H", "J", "K", "L", "M", "N", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"
        ];
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        //是否已存在，存在就回调再随机
        $memModel = new \app\home\model\MemberModel();
        $where = [
            ['invite', '=', $output]
        ];
        $info = $memModel->geetMemberWhereReturnInfo($where, 'member_id');
        if(!empty($info))
        {
            $output = $this->cmf_random_string();
        }
        return $output;
    }



    public function filterEmoji($str = ''){
        $str = json_encode($str);
        $str = json_decode(preg_replace("#(\\\ud[0-9a-f]{3})#i", "", $str));
        return $str;
    }
}